// pages/charge/e_charge_2/e_charge_2.js

const app = getApp() // 获取应用实例
const util = require('../../../utils/util')
import { getInit, getEBalance } from '../../../utils/http/api'
import { openWxPay } from '../../../utils/pay/pay'

Page({

  // 电费第二个页面的初始数据
  data: {

    // 传过来的缴费户号
    account_num: '',
    // 缴费金额
    charge_num: '',
    // 50 100 200 选中状态 0 选中50 1 选中 100 2 选中200
    money_state: 99,
    // 电费余额详情
    balance_detail: {},
    // 电费余额
    balance: 0,

  },

  // 点击50
  on50Click(e) {
    let new_m_state = 0
    let new_c_num = 500
    if (this.data.money_state == 0) {
      new_m_state = 99
      new_c_num = ''
    }
    this.setData({
      money_state: new_m_state,
      charge_num: new_c_num,
    })
  },

  // 点击100
  on100Click(e) {
    let new_m_state = 1
    let new_c_num = 100
    if (this.data.money_state == 1) {
      new_m_state = 99
      new_c_num = ''
    }
    this.setData({
      money_state: new_m_state,
      charge_num: new_c_num,
    })
  },

  // 点击200
  on200Click(e) {
    let new_m_state = 2
    let new_c_num = 200
    if (this.data.money_state == 2) {
      new_m_state = 99
      new_c_num = ''
    }
    this.setData({
      money_state: new_m_state,
      charge_num: new_c_num,
    })
  },

  // 监听金额输入框
  onInput(e) {
    // 监听输入的缴费金额，赋值给记录变量
    this.setData({ charge_num: e.detail.value, })
  },

  // 去缴费
  onToCharge(e) {
    if (util.isNull(this.data.charge_num)) {
      wx.showToast({ title: '请输入缴费金额', icon: 'none' });
      return;
    }
    openWxPay(2, this.data.charge_num, this.data.account_num, '')
  },

  // 请求电费余额 
  async reqBalance() {
    wx.showLoading({ title: '处理中', mask: true, })
    let { code, msg, data } = await getEBalance({ electric: this.data.account_num, token: app.gl.token, })
    // console.log(`reqBalance...code=${code},msg=${msg},data=`, data)
    if (code == '1') {
      this.setData({ balance_detail: data.data, balance: data.data.money })
    } else {
      wx.showToast({ title: msg, icon: 'error' })
    }
  },

  // 初始化支付信息等 
  async reqInit() {
    let { code, msg, data } = await getInit({})
    // console.log(`reqInit...code=${code},msg=${msg},data=`, data)
    if (code == '1') {
      app.gl.wx_appsecret = data[1].value;
    } else {
      console.log(`获取初始化信息错误:${msg}`)
    }
  },

  // 生命周期函数--监听页面加载
  onLoad(options) {
    // 获取初始化支付信息
    this.reqInit()
    // 设置传过来的参数
    this.setData({
      charge_num: options.charge_num,
      account_num: options.account_num,
    })
    // 请求户号余额等信息
    this.reqBalance()
  },

})